﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.BPM.Core.Model;
using NetWing.Common;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NetWing.Common.Data.Filter;

namespace NetWing.BPM.Admin.sys.ashx
{
    /// <summary>
    /// DataSourceFieldHandler 的摘要说明
    /// </summary>
    public class DataSourceFieldHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            UserBll.Instance.CheckUserOnlingState();
            string tablename = context.Request["tablename"];
            string field = context.Request["field"];
            string wherefield= context.Request["wherefield"];
            string wherestr = context.Request["wherestr"];
            string order = context.Request["order"];
            string q = context.Request["q"];//easyui里如果mode 设置为remote格式，文本发生改变时会自动发一个q参数到后台q就是用户输入的文本
            if (!string.IsNullOrEmpty(tablename) && !string.IsNullOrEmpty(field))
            {

                string sql = "select top 500 * from " + tablename + " where ";
   
                //数据权限筛选s
                string sqlwhere = " 1=1 ";
                
                if (SysVisitor.Instance.cookiesIsAdmin=="False"&&tablename!= "Sys_Users"&&tablename!= "MJaccountingSubjects")
                { //判断是否是超管如果是超管理，所有显示
                    sqlwhere = "(depid in (" + SysVisitor.Instance.cookiesDepartments + "))";//如果是超管则不显示
                }

                //数据权限筛选e
                sql = sql + sqlwhere;

                if (!string.IsNullOrEmpty(q))//如果用户查询参数不为空
                {
                    sql = sql+" and " + field + " like '%" + q + "%'";
                }
                //条件1
                if (!string.IsNullOrEmpty(wherefield))//如果用户查询参数不为空
                {
                    sql = sql + " and " + wherefield + " like '%" + wherestr + "%'";
                }


                if (!string.IsNullOrEmpty(order))//如果排序不为空
                {
                    sql = sql + " order by "+order;
                }
                else
                {
                    sql = sql + " order by keyid asc";
                }


                


                DataTable dt = SqlEasy.ExecuteDataTable(sql);

                string jsonString = string.Empty;
                jsonString = JsonConvert.SerializeObject(dt);
                context.Response.Write(jsonString);

            }
            //context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}